<template>
	<div class="banner-management">
		<!-- 搜索区域 -->
		<div class="search-area">
			<el-form :inline="true" :model="searchForm">
				<el-form-item label="轮播图标题">
					<el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
				</el-form-item>
				<el-form-item label="校区名">
					<el-input v-model="searchForm.campusName" placeholder="请输入校区名" clearable />
				</el-form-item>
				<el-form-item label="轮播图类型">
					<el-select style="width: 120px;" v-model="searchForm.bannerType" placeholder="请选择类型" clearable>
						<el-option label="全部" :value="null" />
						<el-option label="课程广告" :value="0" />
						<el-option label="校区广告" :value="1" />
						<el-option label="系统广告" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item label="显示状态">
					<el-select style="width: 120px;" v-model="searchForm.isVisible" placeholder="请选择状态" clearable>
						<el-option label="全部" :value="null" />
						<el-option label="显示" :value="1" />
						<el-option label="隐藏" :value="0" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch">查询</el-button>
					<el-button @click="resetSearch">重置刷新</el-button>
					<el-button type="success" @click="showAddDialog">添加轮播图</el-button>
				</el-form-item>
			</el-form>
		</div>

		<!-- 表格区域 -->
		<div class="table-area">
			<el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
				<el-table-column prop="bannerId" label="ID" width="80" align="center" />
				<el-table-column label="轮播图" width="200" align="center">
					<template #default="{ row }">
						<el-image style="width: 180px; height: 100px" :src="row.imageUrl"
							:preview-src-list="[row.imageUrl]" fit="contain" />
					</template>
				</el-table-column>
				<el-table-column prop="title" label="标题" width="150" align="center" />
				<el-table-column label="跳转链接" width="200" align="center" show-overflow-tooltip>
					<template #default="{ row }">
						{{ row.linkUrl || '-' }}
					</template>
				</el-table-column>
				<el-table-column prop="bannerSort" label="排序" width="50" align="center" />
				<el-table-column label="类型" width="120" align="center">
					<template #default="{ row }">
						{{ getBannerTypeName(row.bannerType) }}
					</template>
				</el-table-column>
				<el-table-column label="关联校区" width="150" align="center">
					<template #default="{ row }">
						{{ row.campusName || '-' }}
					</template>
				</el-table-column>
				<el-table-column label="关联课程" width="150" align="center">
					<template #default="{ row }">
						{{ row.courseName || '-' }}
					</template>
				</el-table-column>
				<el-table-column label="开始时间" width="150" align="center">
					<template #default="{ row }">
						{{ formatDateTime(row.startTime) }}
					</template>
				</el-table-column>
				<el-table-column label="结束时间" width="150" align="center">
					<template #default="{ row }">
						{{ formatDateTime(row.endTime) }}
					</template>
				</el-table-column>
				<el-table-column label="状态" width="80" align="center">
					<template #default="{ row }">
						<el-switch v-model="row.isVisible" :active-value="1" :inactive-value="0" active-color="#13ce66"
							inactive-color="#ff4949" @change="changeStatus(row.bannerId, row.isVisible)" />
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" align="center" fixed="right">
					<template #default="{ row }">
						<el-button size="small" @click="showEditDialog(row)">编辑</el-button>
						<el-button size="small" type="danger" @click="handleDelete(row.bannerId)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 分页 -->
		<div class="pagination-area">
			<el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
				:total="pagination.total" :page-sizes="[5, 10, 20, 30]" layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange" @current-change="handleCurrentChange" />
		</div>

		<!-- 添加轮播图对话框 -->
		<el-dialog v-model="addDialogVisible" title="添加轮播图" width="700px">
			<el-form :model="addForm" label-width="100px" :rules="addRules" ref="addFormRef">
				<el-form-item label="轮播图标题" prop="title">
					<el-input v-model="addForm.title" placeholder="请输入轮播图标题" />
				</el-form-item>
				<el-form-item label="图片链接" prop="imageUrl">
					<el-input v-model="addForm.imageUrl" placeholder="请输入图片URL" />
				</el-form-item>
				<el-form-item label="跳转链接">
					<el-input v-model="addForm.linkUrl" placeholder="请输入跳转链接" />
				</el-form-item>
				<el-form-item label="排序权重" prop="bannerSort">
					<el-input-number v-model="addForm.bannerSort" :min="0" :max="999" />
					<span class="tip">(数字越大越靠前)</span>
				</el-form-item>
				<el-form-item label="显示状态" prop="isVisible">
					<el-switch v-model="addForm.isVisible" :active-value="1" :inactive-value="0" />
				</el-form-item>
				<el-form-item label="展示时间">
					<el-date-picker v-model="addForm.timeRange" type="datetimerange" range-separator="至"
						start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitAddForm">确定</el-button>
			</template>
		</el-dialog>

		<!-- 编辑轮播图对话框 -->
		<el-dialog v-model="editDialogVisible" title="编辑轮播图" width="700px">
			<el-form :model="editForm" label-width="100px" ref="editFormRef">
				<el-form-item label="轮播图标题" prop="title">
					<el-input v-model="editForm.title" />
				</el-form-item>
				<el-form-item label="图片链接">
					<el-input v-model="editForm.imageUrl" disabled />
				</el-form-item>
				<el-form-item label="跳转链接">
					<el-input v-model="editForm.linkUrl" disabled />
				</el-form-item>
				<el-form-item label="排序权重" prop="bannerSort">
					<el-input-number v-model="editForm.bannerSort" :min="0" :max="999" />
				</el-form-item>
				<el-form-item label="轮播图类型">
					<el-input :value="getBannerTypeName(editForm.bannerType)" disabled />
				</el-form-item>
				<el-form-item label="关联校区">
					<el-input :value="editForm.campusName || '-'" disabled />
				</el-form-item>
				<el-form-item label="关联课程">
					<el-input :value="editForm.courseName || '-'" disabled />
				</el-form-item>
				<el-form-item label="显示状态" prop="isVisible">
					<el-switch v-model="editForm.isVisible" :active-value="1" :inactive-value="0" />
				</el-form-item>
				<el-form-item label="开始时间">
					<el-input :value="formatDateTime(editForm.startTime)" disabled />
				</el-form-item>
				<el-form-item label="结束时间">
					<el-input :value="formatDateTime(editForm.endTime)" disabled />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitEditForm">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		getBannerPage,
		addBanner,
		updateBanner,
		deleteBanner,
		changeBannerStatus
	} from '@/api/banner'

	// 数据定义
	const tableData = ref([])
	const loading = ref(false)
	const addDialogVisible = ref(false)
	const editDialogVisible = ref(false)
	const addFormRef = ref()
	const editFormRef = ref()

	// 搜索表单
	const searchForm = reactive({
		title: '',
		campusName: '',
		bannerType: null,
		isVisible: null
	})

	// 分页数据
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 添加表单数据
	const addForm = reactive({
		title: '',
		imageUrl: '',
		linkUrl: '',
		bannerSort: 0,
		isVisible: 1,
		timeRange: []
	})

	// 添加表单验证规则
	const addRules = reactive({
		title: [{
			required: true,
			message: '请输入标题',
			trigger: 'blur'
		}],
		imageUrl: [{
			required: true,
			message: '请输入图片链接',
			trigger: 'blur'
		}],
		bannerSort: [{
			required: true,
			message: '请输入排序权重',
			trigger: 'blur'
		}]
	})

	// 编辑表单数据
	const editForm = reactive({
		bannerId: null,
		title: '',
		imageUrl: '',
		linkUrl: '',
		bannerSort: 0,
		bannerType: null,
		courseName: '',
		campusName: '',
		isVisible: 1,
		startTime: '',
		endTime: ''
	})

	// 轮播图类型映射
	const bannerTypeMap = {
		0: '课程广告',
		1: '校区广告',
		2: '系统广告'
	}

	// 初始化加载数据
	onMounted(() => {
		fetchBannerList()
	})

	// 获取轮播图列表
	const fetchBannerList = async () => {
		try {
			loading.value = true
			const params = {
				currentPage: pagination.currentPage,
				pageSize: pagination.pageSize,
				...searchForm
			}
			const res = await getBannerPage(params)
			if (res.code === 200) {
				tableData.value = res.data.page.records
				pagination.total = res.data.page.total
			}
		} catch (error) {
			console.error('获取轮播图列表失败:', error)
			ElMessage.error('获取轮播图列表失败')
		} finally {
			loading.value = false
		}
	}

	// 查询
	const handleSearch = () => {
		pagination.currentPage = 1
		fetchBannerList()
	}

	// 重置搜索
	const resetSearch = () => {
		searchForm.title = ''
		searchForm.campusName = ''
		searchForm.bannerType = null
		searchForm.isVisible = null
		handleSearch()
	}

	// 分页大小变化
	const handleSizeChange = (val) => {
		pagination.pageSize = val
		fetchBannerList()
	}

	// 当前页变化
	const handleCurrentChange = (val) => {
		pagination.currentPage = val
		fetchBannerList()
	}

	// 显示添加对话框
	const showAddDialog = () => {
		resetAddForm()
		addDialogVisible.value = true
	}

	// 重置添加表单
	const resetAddForm = () => {
		addFormRef.value?.resetFields()
		Object.assign(addForm, {
			title: '',
			imageUrl: '',
			linkUrl: '',
			bannerSort: 0,
			isVisible: 1,
			timeRange: []
		})
	}

	// 提交添加表单
	const submitAddForm = async () => {
		try {
			await addFormRef.value.validate()

			const params = {
				...addForm,
				bannerType: 2, // 固定为系统广告类型
				startTime: addForm.timeRange[0],
				endTime: addForm.timeRange[1]
			}

			await addBanner(params)
			ElMessage.success('添加成功')
			addDialogVisible.value = false
			fetchBannerList()
		} catch (error) {
			console.error('添加失败:', error)
		}
	}

	// 显示编辑对话框
	const showEditDialog = (row) => {
		Object.assign(editForm, {
			bannerId: row.bannerId,
			title: row.title,
			imageUrl: row.imageUrl,
			linkUrl: row.linkUrl,
			bannerSort: row.bannerSort,
			bannerType: row.bannerType,
			courseName: row.courseName,
			campusName: row.campusName,
			isVisible: row.isVisible,
			startTime: row.startTime,
			endTime: row.endTime
		})
		editDialogVisible.value = true
	}

	// 提交编辑表单
	const submitEditForm = async () => {
		try {
			const params = {
				bannerId: editForm.bannerId,
				title: editForm.title,
				bannerSort: editForm.bannerSort,
				isVisible: editForm.isVisible
			}

			await updateBanner(params)
			ElMessage.success('更新成功')
			editDialogVisible.value = false
			fetchBannerList()
		} catch (error) {
			console.error('更新失败:', error)
			ElMessage.error('更新失败')
		}
	}

	// 删除轮播图
	const handleDelete = async (id) => {
		try {
			await ElMessageBox.confirm('确定要删除该轮播图吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})

			await deleteBanner(id)
			ElMessage.success('删除成功')
			fetchBannerList()
		} catch (error) {
			if (error !== 'cancel') {
				ElMessage.error('删除失败')
			}
		}
	}

	// 修改状态
	const changeStatus = async (id, isVisible) => {
		try {
			await changeBannerStatus(id, isVisible)
			ElMessage.success('状态更新成功')
		} catch (error) {
			console.error('状态更新失败:', error)
			ElMessage.error('状态更新失败')
			// 恢复原状态
			const item = tableData.value.find(item => item.bannerId === id)
			if (item) item.isVisible = isVisible === 1 ? 0 : 1
		}
	}

	// 格式化日期时间
	const formatDateTime = (dateStr) => {
		if (!dateStr) return '-'
		try {
			const date = new Date(dateStr)
			return date.toLocaleString()
		} catch (e) {
			return dateStr
		}
	}

	// 获取轮播图类型名称
	const getBannerTypeName = (type) => {
		return bannerTypeMap[type] || '未知类型'
	}
</script>

<style scoped>
	.banner-management {
		padding: 20px;
		background-color: #fff;
	}

	.search-area {
		margin-bottom: 20px;
	}

	.pagination-area {
		margin-top: 20px;
		display: flex;
		justify-content: flex-end;
	}

	.tip {
		margin-left: 10px;
		color: #999;
		font-size: 12px;
	}
</style>